package com.swjsj.hsk;

import org.apache.commons.mail.EmailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 项目名：springboot
 * <a href="mailto:16009413@qq.com">sily</a> 在 2015/11/25 13:42 创建了文件
 * 说明：
 */
@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {

    @Autowired
    SendSimpleEmail sse;
    @Autowired
    IPCompared ipCompared;

    private static Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    @Scheduled(fixedRate = 1000 * 5)
    public void reportCurrentTime() {
        System.out.println("Scheduling Tasks Examples: The time is now " + dateFormat().format(new Date()));
    }

    //每1分钟执行一次
    @Scheduled(cron = "0 */1 *  * * * ")
    public void reportCurrentByCron() {
        System.out.println("定时域名同步开始时间： " + dateFormat().format(new Date()));
        try {
            String ipStr = ipCompared.ipComp();
            if (StringUtils.isNotNull(ipStr)) {
                //SendSimpleEmail sse = new SendSimpleEmail("花生壳的动态ip不正确", ipStr);
                sse.setSubject("花生壳的动态ip不正确");
                sse.setMsg(ipStr);
                sse.getInitDataByConfig();
                try {
                    sse.send();
                } catch (EmailException e) {
                    log.error(e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        System.out.println("定时域名同步结束时间： " + dateFormat().format(new Date()));
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
}
